var _ = require('lodash'),
    PublicEnum = require('../../../Base/server/controllers/Enum'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller');

// 交接区入库：写入库记录
exports.addStockQty = function(userID, barcodes, completeFun) {
    barcodeMasterController.findBarcodeMasters(barcodes, function(err, records) {
        if (err || !records) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '不能识别的条码，请检查查询参数！';
            completeFun(newErr);
            return;
        }
        var rcvRecords = [];
        _.forEach(records, function(record) {
            rcvRecords.push({
                RowStatus: PublicEnum.RowStatus.Insert,
                CreatedBy: userID,
                BarcodeMaster: record._id,
                RcvBusinessType: 1,
                BusinessDocID: record.MO,
                LotNumber: record.MOLotNumber,
                ItemMaster: record.ItemMaster,
                RcvUser: userID,
                RcvQty: 1,
                RcvOperation: record.Operation,
                BizRecord: record.BizRecord,
                ConnectArea: record.Operation ? record.Operation.ConnectArea : ''
            });
        });
        var entity = entityCollection.getEntity("RcvRecord");
        entity.save(rcvRecords, function(err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '新增错误';
                newErr.message = '新增入库记录错误，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, records);
            }
        });
    });
};
//查询出入库记录，工单信息
exports.queryRcvRecords = function(completeFun) {
    var rcvRecordEntity = entityCollection.getEntity("RcvRecord");
    var gtDate = new Date();
    gtDate.setHours(0);
    gtDate.setMinutes(0);
    gtDate.setSeconds(0);
    gtDate.setMilliseconds(0);

    var gtDateCopy = new Date();
    gtDateCopy.setHours(0);
    gtDateCopy.setMinutes(0);
    gtDateCopy.setSeconds(0);
    var Milliseconds = 24 * 60 * 60 * 1000;
    var ltDate = new Date(gtDateCopy.setMilliseconds(0) + Milliseconds);
    rcvRecordEntity.find({
            RcvBusinessType: 0,
            RcvDateTime: { $gte: gtDate, $lt: ltDate }
        },
        null, [{
            path: "BarcodeMaster",
            select: "ShipLotNumber MOLotNumber MO",
            populate: [{
                path: "MO",
                select: "Customer",
                model: 'MO'
            }]
        }],
        function(err, records) {
            if (err) {
                completeFun(err);
            }

            var recordObj = {};
            _.forEach(records, function(record) {
                if (record.BarcodeMaster && !recordObj[record.BarcodeMaster.MOLotNumber]) {
                    recordObj[record.BarcodeMaster.MOLotNumber] = {
                        ShipLotNumber: record.BarcodeMaster.ShipLotNumber ? record.BarcodeMaster.ShipLotNumber : "",
                        MOLotNumber: record.BarcodeMaster.MOLotNumber ? record.BarcodeMaster.MOLotNumber : "",
                        Customer: record.BarcodeMaster.MO ? record.BarcodeMaster.MO.Customer : "",
                        Count: 0
                    };
                }
                if (recordObj[record.BarcodeMaster.MOLotNumber]) {
                    recordObj[record.BarcodeMaster.MOLotNumber].Count += 1;
                }
            });
            var recordArr = [];
            for (var item in recordObj) {
                recordArr.push(recordObj[item]);
            }
            recordArr.sort(ArraySortByKey("MOLotNumber"));
            completeFun(null, recordArr);
        });
};

//根据条码主档查询入库记录
exports.queryRcvRecordsByBarcodeMaster = function(barcodeMaster, completeFun) {
    var entity = entityCollection.getEntity("RcvRecord");
    entity.findOne({ BarcodeMaster: barcodeMaster }, null, function(err, record) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, record);
        }
    });
};

//批量查询入库记录
exports.queryByCondition = function(condition, completeFun) {
    var entity = entityCollection.getEntity("RcvRecord");
    entity.find(condition, null, null, function(err, records) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, records);
        }
    });
};
//数组排序
function ArraySortByKey(key) {
    return function(objFirst, objSecond) {
        var aStr, bStr;
        if (typeof objFirst === "object" && typeof objSecond === "object" && objFirst && objSecond) {
            aStr = objFirst[key];
            bStr = objSecond[key];
            if (aStr === bStr) {
                return 0;
            }
            if (typeof aStr === typeof bStr) {
                return aStr < bStr ? -1 : 1;
            }
            return typeof aStr < typeof bStr ? -1 : 1;
        } else {
            throw ("error");
        }
    }
}
